package com.test.datasource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author loocao
 */
@Component
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Autowired
    public DynamicDataSource(
            @Qualifier(DataSourceDefine.DATASOURCE_PARK) DataSource parkDataSource,
            @Qualifier(DataSourceDefine.DATASOURCE_UNIANCE) DataSource unianceDataSource) {
        super();

        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DataSourceDefine.DATASOURCE_PARK, parkDataSource);
        targetDataSources.put(DataSourceDefine.DATASOURCE_UNIANCE, unianceDataSource);

        setTargetDataSources(targetDataSources);
        setDefaultTargetDataSource(parkDataSource);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceHolder.getDateSoureType();
    }

}
